package model

import (
	"encoding/json"
	"fmt"
	"io/fs"
	"log"
	"net/http"
	"time"
)
// WebServer 结构体管理Web服务器
type WebServer struct {
	login   *Login
	port    int
	version string
	webFS   fs.FS // 嵌入的web资源文件系统
}

// NewWebServer 创建新的Web服务器实例
func NewWebServer(login *Login, port int, version string, webFS fs.FS) *WebServer {
	return &WebServer{
		login:   login,
		port:    port,
		version: version,
		webFS:   webFS,
	}
}

// Start 启动Web服务器
func (ws *WebServer) Start() error {
	// 设置HTTP路由
	http.HandleFunc("/", ws.handleIndex)
	http.HandleFunc("/api/domains", ws.handleDomainsAPI)
	http.HandleFunc("/api/status", ws.handleStatusAPI)

	// 静态文件服务 - 使用传入的web资源
	webSubFS, err := fs.Sub(ws.webFS, "web")
	if err != nil {
		return fmt.Errorf("创建web子文件系统失败: %v", err)
	}
	http.Handle("/web/", http.StripPrefix("/web/", http.FileServer(http.FS(webSubFS))))

	addr := fmt.Sprintf(":%d", ws.port)
	log.Printf("Web服务器启动在 http://localhost:%d", ws.port)

	return http.ListenAndServe(addr, nil)
}

// handleIndex 处理首页请求
func (ws *WebServer) handleIndex(w http.ResponseWriter, r *http.Request) {
	log.Printf("接收到页面请求: %s %s", r.Method, r.URL.Path)
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	// 重定向到Web界面
	http.Redirect(w, r, "/web/", http.StatusFound)
}

// handleDomainsAPI 处理域名列表API请求
func (ws *WebServer) handleDomainsAPI(w http.ResponseWriter, r *http.Request) {
	log.Printf("接收到API请求: %s %s", r.Method, r.URL.Path)
	// 获取域名解析信息
	err := ws.login.GetParseList()
	if err != nil {
		http.Error(w, fmt.Sprintf("获取域名列表失败: %v", err), http.StatusInternalServerError)
		return
	}

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	// 过滤出配置文件中指定的DDNS记录
	filteredDomains := []DomainInfo{}
	configSub4 := ws.login.Domain.Domain.Sub4
	configSub6 := ws.login.Domain.Domain.Sub6
	
	for _, domain := range ws.login.DomainInfoList {
		// 只保留配置文件中指定的子域名记录
		if domain.Sub == configSub4 || domain.Sub == configSub6 {
			filteredDomains = append(filteredDomains, domain)
		}
	}

	// 对域名列表进行去重处理
	deduplicatedDomains := ws.removeDuplicateDomainInfos(filteredDomains)

	// 构建响应数据
	response := map[string]interface{}{
		"success":   true,
		"domains":   deduplicatedDomains,
		"count":     len(deduplicatedDomains),
		"timestamp": time.Now().Unix(),
	}

	// 编码JSON响应
	err = json.NewEncoder(w).Encode(response)
	if err != nil {
		http.Error(w, fmt.Sprintf("JSON编码失败: %v", err), http.StatusInternalServerError)
		return
	}
}

// 移除重复的域名记录
// 基于Sub、Type和Ip字段进行去重
func (ws *WebServer) removeDuplicateDomainInfos(domains []DomainInfo) []DomainInfo {
	if len(domains) <= 1 {
		return domains
	}
	
	seen := make(map[string]bool)
	var result []DomainInfo
	
	for _, domain := range domains {
		// 创建一个唯一键，基于Sub、Type和Ip字段
		key := fmt.Sprintf("%s-%s-%s", domain.Sub, domain.Type, domain.Ip)
		
		// 如果这个键没有被见过，就添加到结果中
		if !seen[key] {
			seen[key] = true
			result = append(result, domain)
		}
	}
	
	return result
}

// handleStatusAPI 处理状态API请求
func (ws *WebServer) handleStatusAPI(w http.ResponseWriter, r *http.Request) {
	log.Printf("接收到API请求: %s %s", r.Method, r.URL.Path)
	// 设置响应头
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	// 构建状态响应
	status := map[string]interface{}{
		"success":   true,
		"version":   ws.version,
		"status":    "running",
		"timestamp": time.Now().Unix(),
		"config": map[string]interface{}{
			"domain": ws.login.Domain.Domain,
			"type":   ws.login.Domain.Domain.Type,
		},
	}

	// 编码JSON响应
	err := json.NewEncoder(w).Encode(status)
	if err != nil {
		http.Error(w, fmt.Sprintf("JSON编码失败: %v", err), http.StatusInternalServerError)
		return
	}
}
